package com.hefan.api.controller.monitor;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ImCustomMsgEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.api.service.monitor.LiveMonitorLocalService;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LiveRoomVo;
import com.hefan.live.bean.WarnLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: criss
 * Date: 2016/11/2
 * Time: 19:14
 */
@Controller
@RequestMapping("/v1/liveMonitor")
public class LiveMonitorsController {

    private Logger logger = LoggerFactory.getLogger(LiveMonitorsController.class);

    @Resource
    LiveMonitorLocalService liveMonitorLocalService;


    /**
     * 直播断流接口
     * @param request
     * @return
     */
    @RequestMapping("/closeLiving")
    @ResponseBody
    public String closeLiving(HttpServletRequest request) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map params = HttpUtils.initParam(request, HashMap.class);
            if(CollectionUtils.isEmpty(params) || !params.containsKey("userId")
                    || !params.containsKey("chatRoomId")
                    || !params.containsKey("liveUuid")) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }

            String userId = String.valueOf(params.get("userId"));
            String chartRoomId = String.valueOf(params.get("chatRoomId"));
            String liveUuid = String.valueOf(params.get("liveUuid"));
            String promptCopy = MapUtils.getStrValue(params, "promptCopy", "");
            if(StringUtils.isBlank(userId) || StringUtils.isBlank(chartRoomId) ||  StringUtils.isBlank(liveUuid)) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException,null));
            }
            //直播断流处理
            resultBean = liveMonitorLocalService.closeLivingOpreate(userId, chartRoomId, liveUuid,promptCopy);
        } catch (Exception e) {
            logger.error( "class:"+this.getClass().getSimpleName()+"method:closeLiving:"+e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UnknownException,null));
        }
        return  JSON.toJSONString(resultBean);
    }

    /**
     * 监控警告(保存警告日志，发送警告广播)
     * @Title: warningLiving
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws
     * @date:   2016年10月29日 下午2:30:34
     */
    @RequestMapping("/warningLiving")
    @ResponseBody
    public String warningLiving(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try {
            //接参
            WarnLog wlParam = HttpUtils.initParam(request, WarnLog.class);
            if (null == wlParam) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            Map params = HttpUtils.initParam(request, HashMap.class);
            String anchorWaringMsg = ImCustomMsgEnum.AnchorWaringMsg.getMsg();
            if(params.containsKey("anchorWaringMsg") && !StringUtils.isBlank((String)params.get("anchorWaringMsg"))) {
                anchorWaringMsg = (String)params.get("anchorWaringMsg");
            }
            if (StringUtils.isBlank(wlParam.getUserId()) || wlParam.getChatRoomId() <=0 || StringUtils.isBlank(wlParam.getLiveUuid())){
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            int us = this.liveMonitorLocalService.warningLiving(wlParam,anchorWaringMsg);
            if (us <= 0) {
                res.setCode(ResultCode.UNSUCCESS.get_code());
                res.setMsg(ResultCode.UNSUCCESS.getMsg());
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            logger.error("警告失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 将主播设为高危
     * @Title: highStatusLiving
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午2:36:43
     */
    @RequestMapping("/highStatusLiving")
    @ResponseBody
    public String highStatusLiving(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            // 接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "");
            String liveUuid = MapUtils.getStrValue(paramMap, "liveUuid", "");
            int risk = MapUtils.getIntValue(paramMap, "risk", 1);
            String optUserId = MapUtils.getStrValue(paramMap, "optUserId", "");
            if (StringUtils.isBlank(userId)) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("主播盒饭ID参数错误");
                return JSON.toJSONString(res);
            }
            if (risk !=1 && risk !=2) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("设置类型参数错误");
                return JSON.toJSONString(res);
            }
            this.liveMonitorLocalService.LiveRoomHighStatus(userId,liveUuid,risk,optUserId);
        } catch (Exception e) {
            logger.error("将主播设为高危失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 获取违规处罚类型列表
     *
     * @Title: getPunishTypeList
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午3:53:57
     */
    @RequestMapping("/getPunishTypeList")
    @ResponseBody
    public String getPunishTypeList(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        try {
            List list = this.liveMonitorLocalService.getPunishTypeList();
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setMsg(ResultCode.SUCCESS.getMsg());
            res.setData(list);
        } catch (Exception e) {
            logger.error("获取违规处罚类型失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 主播直播提交处罚
     *
     * @Title: dealPunishDetal
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午7:28:13
     */
    @RequestMapping("/dealPunishDetal")
    @ResponseBody
    public String dealPunishDetal(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            // 接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "");
            String liveUuid = MapUtils.getStrValue(paramMap, "liveUuid", "");
            String optUserId = MapUtils.getStrValue(paramMap, "optUserId", "");
            String punishReason = MapUtils.getStrValue(paramMap, "punishReason", "");
            String illegalPic = MapUtils.getStrValue(paramMap, "illegalPic", "");
            int category = MapUtils.getIntValue(paramMap, "category", 0);
            long typeId = MapUtils.getLongValue(paramMap, "typeId", 0);
            if (StringUtils.isBlank(userId)) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("主播盒饭ID参数错误");
                return JSON.toJSONString(res);
            }
            // 监控暂无登录，暂不校验
			/*
			 * if(StringUtils.isBlank(optUserId)){
			 * res.setCode(ResultCode.ParamException.get_code());
			 * res.setMsg("主播盒饭ID参数错误"); return JSON.toJSONString(res); }
			 */
            if (category < 0 || typeId < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("违规或处罚类型错误");
                return JSON.toJSONString(res);
            }
            Map map = this.liveMonitorLocalService.getPunishTypeById(typeId,0);
            if (map == null || map.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("违规或处罚类型错误");
                return JSON.toJSONString(res);
            }
            int ur = this.liveMonitorLocalService.dealPunishDetal(userId, optUserId, map, punishReason, illegalPic,liveUuid,0,0);
            if (ur <= 0) {
                res.setCode(ResultCode.UNSUCCESS.get_code());
                res.setMsg(ResultCode.UNSUCCESS.getMsg());
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            logger.error("提交处罚失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 用户资料违规处罚
     * @param request
     * @return
     */
    @RequestMapping("/dealPunishDataDetal")
    @ResponseBody
    public String dealPunishDataDetal(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            // 接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "");
            String optUserId = MapUtils.getStrValue(paramMap, "optUserId", "");
            String punishReason = MapUtils.getStrValue(paramMap, "punishReason", "");
            int category = MapUtils.getIntValue(paramMap, "category", 0);
            long typeId = MapUtils.getLongValue(paramMap, "typeId", 0);
            int punishDataType = MapUtils.getIntValue(paramMap, "punishDataType", 0);
            if (StringUtils.isBlank(userId)) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("用户盒饭ID参数错误");
                return JSON.toJSONString(res);
            }
            // 监控暂无登录，暂不校验
			/*
			 * if(StringUtils.isBlank(optUserId)){
			 * res.setCode(ResultCode.ParamException.get_code());
			 * res.setMsg("主播盒饭ID参数错误"); return JSON.toJSONString(res); }
			 */
            if (category < 0 || typeId < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("违规或处罚类型错误");
                return JSON.toJSONString(res);
            }
            if (punishDataType < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("资料类型错误");
                return JSON.toJSONString(res);
            }
            Map map = this.liveMonitorLocalService.getPunishTypeById(typeId,1);
            if (map == null || map.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("违规或处罚类型错误");
                return JSON.toJSONString(res);
            }
            int ur = this.liveMonitorLocalService.dealPunishDetal(userId, optUserId, map, punishReason, " ","1",1,punishDataType);
            if (ur <= 0) {
                res.setCode(ResultCode.UNSUCCESS.get_code());
                res.setMsg(ResultCode.UNSUCCESS.getMsg());
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            logger.error("提交处罚失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }


    /**
     * 处罚列表
     *
     * @Title: dealPunishDetal
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午7:28:13
     */
    @RequestMapping("/getPunishList")
    @ResponseBody
    public String getPunishList(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            List list = liveMonitorLocalService.getPunishList();
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setData(list);
        } catch (Exception e) {
            logger.error("获取处罚列表失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 直播列表
     *
     * @Title: dealPunishDetal
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午7:28:13
     */
    @RequestMapping("/getLivingList")
    @ResponseBody
    public String getLivingList(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            Page po = new Page();
            Map paramMap = HttpUtils.initParam(request, Map.class);
            po.pageNo = MapUtils.getIntValue(paramMap, "pageNo", po.pageNo);
            po.pageSize = MapUtils.getIntValue(paramMap, "pageSize", po.pageSize);
            res.setCode(ResultCode.SUCCESS.get_code());
            List<LiveRoomVo> list = liveMonitorLocalService.getLivingList(po);
            res.setData(list);
        } catch (Exception e) {
            logger.error("获取直播间列表失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 直播明细
     *
     * @Title: dealPunishDetal
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param request
     * @return
     * @return: String
     * @author: LiTeng
     * @throws @date:
     *             2016年10月29日 下午7:28:13
     */
    @RequestMapping("/getLivingInfo")
    @ResponseBody
    public String findLiveRoomByIdFormonitor(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "");
            String uuid = MapUtils.getStrValue(paramMap, "liveUuid", "");
            res.setCode(ResultCode.SUCCESS.get_code());
            LiveRoomVo liveRoomVo = liveMonitorLocalService.findLiveRoomByIdFormonitor(userId, uuid);
            res.setData(liveRoomVo);
        } catch (Exception e) {
            logger.error("获取直播间明细失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 获取高危视频库
     * @Title: getHighRiskLiveList   
     * @Description: TODO(这里用一句话描述这个方法的作用)   
     * @param request
     * @return      
     * @return: String
     * @author: LiTeng      
     * @throws 
     * @date:   2016年11月24日 下午2:21:06
     */
    @RequestMapping("/getHighRiskLiveList")
    @ResponseBody
    public String getHighRiskLiveList(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        try {
            // 接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "");
            String nickName = MapUtils.getStrValue(paramMap, "nickName", "");
            String startTime = MapUtils.getStrValue(paramMap, "startTime", "");
            String endTime = MapUtils.getStrValue(paramMap, "endTime", "");
            List list = this.liveMonitorLocalService.getHighRiskLiveList(userId,nickName,startTime,endTime);
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setData(list);
        } catch (Exception e) {
            logger.error("获取高危视频库失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }
    
    /**
     * 修改直播间信息
     * @Title: updateLivingInfo   
     * @Description: TODO(这里用一句话描述这个方法的作用)   
     * @param request
     * @return      
     * @return: String
     * @author: LiTeng      
     * @throws 
     * @date:   2016年12月6日 下午3:43:27
     */
    @RequestMapping("/updateLivingInfo")
    @ResponseBody
    public String updateLivingInfo(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        String userId;
		String uuid;
		try {
			Map paramMap = HttpUtils.initParam(request, Map.class);
			if (null == paramMap || paramMap.isEmpty()) {
			    res.setCode(ResultCode.ParamException.get_code());
			    res.setMsg(ResultCode.ParamException.getMsg());
			    return JSON.toJSONString(res);
			}
			userId = MapUtils.getStrValue(paramMap, "userId", "");
			uuid = MapUtils.getStrValue(paramMap, "liveUuid", "");
			int upType = MapUtils.getIntValue(paramMap, "upType", 0);
			if(StringUtils.isBlank(userId)){
				 res.setCode(ResultCode.ParamException.get_code());
			     res.setMsg("盒饭ID不能为空!");
			     return JSON.toJSONString(res);
			}
			if(StringUtils.isBlank(uuid)){
			 	res.setCode(ResultCode.ParamException.get_code());
			    res.setMsg("直播uuid不能为空");
			    return JSON.toJSONString(res);
			}
			if(upType !=1 && upType !=2){
				res.setCode(ResultCode.ParamException.get_code());
			    res.setMsg("修改类型不合法");
			    return JSON.toJSONString(res);
			}
			String liveName = "";
			String liveImg = "";
			if(upType == 1){
				liveName = DynamicProperties.getString("default.live.name");
			}else if(upType ==2){
				liveImg = DynamicProperties.getString("default.live.img");
			}
			res = liveMonitorLocalService.updateLiveInfoForMonitor(liveName, liveImg, uuid, userId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("修改直播间信息失败：" + e.getMessage());
            res.setCode(ResultCode.UnknownException.get_code());
            res.setMsg(ResultCode.UnknownException.getMsg());
            return JSON.toJSONString(res);
		}
        return JSON.toJSONString(res);
    }
}
